/********************************************************************************
 * FeedbackServiceDelegator.java
 *
 * Created by Jigar Mistry
 * Last modified Date: Sep 5, 2008 3:00:48 PM by Nishan
 * Version : 0.1
 * Copyright (c) 2008 - 2009 cyberThink Infotech Pvt. Ltd., All rights reserved.
 ********************************************************************************/

package com.printeverywhere.delegator;

import java.math.BigDecimal;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import com.printeverywhere.dto.FeedBackCount;
import com.printeverywhere.dto.Feedback;
import com.printeverywhere.dto.User;
import com.printeverywhere.util.HibernateUtil;
import com.printeverywhere.util.SearchCriteria;
import static com.printeverywhere.util.LoggerConstants.*;
import static com.printeverywhere.util.AttributeConstants.*;

/**
 * The Class FeedbackServiceDelegator.
 */
public class FeedbackServiceDelegator {

	/** The log. */
	private static Logger log = Logger.getLogger(FeedbackServiceDelegator.class);
	private static final String sql ="select  sum(positive+neutral+negative) as total, sum(positive) as positive , sum(neutral) as neu ,sum(negative) as neg from feedback";
	/**
	 * Gets the feedback list by user id.
	 *
	 * @param searchCriteria the search criteria
	 *
	 * @return the feedback list by user id
	 *
	 * @throws HibernateException the hibernate exception
	 */
	public static List<Feedback> getFeedbackListByUserId(SearchCriteria searchCriteria) throws HibernateException {
		if(log.isInfoEnabled()){
			log.info("Getting list for user with search criteria".intern());
		}
		Session session = HibernateUtil.getSession();
		try {
			Transaction transaction = session.beginTransaction();
			Criteria criteria = session.createCriteria(Feedback.class);
			Set<String> keys = searchCriteria.getAttributeNames();
			Iterator<String> it = keys.iterator();
			String key = null;
			Object value = null;

			while (it.hasNext()) {
				key = it.next();
				value = searchCriteria.getAttribute(key);
				criteria.add(Restrictions.eq(key, value));
			}

			List<Feedback> feedbackList = criteria.list();
			transaction.commit();
			return feedbackList;
		} catch (HibernateException e) {
			log.error("Got exception when getting list for user with search criteria".intern());
			throw e;
		} finally {
			if(log.isInfoEnabled()){
				log.info("Closing session".intern());
			}
			session.flush();
			session.close();
		}
	}

	public static Feedback getFeedbackByUserItemId(SearchCriteria searchCriteria) throws HibernateException {
		if(log.isInfoEnabled()){
			log.info("Getting list for feedback by user and Item id".intern());
		}
		Session session = HibernateUtil.getSession();
		try {
			Transaction transaction = session.beginTransaction();
			Criteria criteria = session.createCriteria(Feedback.class);
			Set<String> keys = searchCriteria.getAttributeNames();
			Iterator<String> it = keys.iterator();
			String key = null;
			Object value = null;

			while (it.hasNext()) {
				key = it.next();
				value = searchCriteria.getAttribute(key);
				criteria.add(Restrictions.eq(key, value));
			}

			List<Feedback> feedbackList = criteria.list();
			transaction.commit();
			return (Feedback) ((feedbackList.size() == 0) ? null : feedbackList.get(0));
		} catch (HibernateException e) {
			log.error("Got exception when getting list for user without search criteria".intern());
			throw e;
		} finally {
			if(log.isInfoEnabled()){
				log.info("Closing session".intern());
			}
			session.flush();
			session.close();
		}
	}

	/**
	 * Insert feedback.
	 *
	 * @param feedback the feedback
	 *
	 * @throws HibernateException the hibernate exception
	 */
	public static void insertFeedback(Feedback feedback) throws HibernateException {
		if(log.isInfoEnabled()){
			log.info("Called insertFeedback method".intern());
		}
		Session session = HibernateUtil.getSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			session.save(feedback);
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
			log.error("Got exception when insert feedback".intern());
			if (tx != null)
				tx.rollback();
		} finally {
			if(log.isInfoEnabled()){
				log.info("Closing session".intern());
			}
			session.flush();
			session.close();
		}
	}

	/**
	 * Update feedback.
	 *
	 * @param feedback the feedback
	 *
	 * @throws HibernateException the hibernate exception
	 */
	public static void updateFeedback(Feedback feedback) throws HibernateException {
		if(log.isInfoEnabled()){
			log.info("Called updateFeedback method".intern());
		}
		Session session = HibernateUtil.getSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			session.update(feedback);
			tx.commit();
		} catch (RuntimeException e) {
			log.error("Got exception when update feedback".intern());
			if (tx != null)
				tx.rollback();
			throw e;
		} finally {
			if(log.isInfoEnabled()){
				log.info("Closing session".intern());
			}
			session.flush();
			session.close();
		}
	}

	/**
	 * Gets the count.
	 *
	 * @return the count
	 *
	 * @author ankur
	 */
	public static FeedBackCount getCount(){
		if(log.isInfoEnabled()){
			log.info(FEEDBACK_USER_COUNT);
		}
		Session session = HibernateUtil.getSession();
		try {
			Transaction transaction = session.beginTransaction();

			List<?> feedbackList = CommonFunctionDelegator.executeSQLQuery(sql);
			transaction.commit();
			Object[] objects = (Object[])feedbackList.iterator().next();
			if(objects[0]!=null && objects[1]!=null && objects[2]!=null && objects[3]!=null){
			return new FeedBackCount(((BigDecimal)objects[0]).intValue(),((BigDecimal)objects[1]).intValue(),((BigDecimal)objects[2]).intValue(),((BigDecimal)objects[3]).intValue());
			}
			else{
				return new FeedBackCount(0,0,0,0);
			}
		} catch (HibernateException e) {
			log.error(USERLISTSEARCHCRITERIAEXCEPTION);
			throw e;
		} finally {
			if(log.isInfoEnabled()){
				log.info(CLOSING_SESSION);
			}
			session.flush();
			session.close();
		}
	}
}